package cn.rengy.web.framework.wxmp.redpacket;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.rengy.tpa.wxmp.pay.exception.PayApiException;
import cn.rengy.tpa.wxmp.pay.exception.PayBusinessException;
import cn.rengy.tpa.wxmp.pay.exception.SignatureException;
import cn.rengy.tpa.wxmp.redpacket.TransfersRO;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.WxAppService;
import cn.rengy.web.framework.wxmp.WxMerchant;
import cn.rengy.web.framework.wxmp.WxMerchantService;

/**
 * 企业付款
 * @author rengy
 *
 */
@Service
public class TransfersService {
	private static Logger logger = LoggerFactory.getLogger(TransfersService.class);
	@Autowired
	private WxAppService wxAppService;
	private BigDecimal fen=new BigDecimal(100);
	@Autowired
	private DbService dbService;
	@Autowired
	private WxMerchantService wxMerchantService;
	/**
	 * 企业付款到零钱
	 * @param wxAccountId
	 * @param user_id
	 * @param openid
	 * @param payAmount
	 * @param payDesc
	 * @param request
	 * @return 系统订单号
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws CertificateException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyStoreException 
	 * @throws PayBusinessException 
	 * @throws PayApiException 
	 * @throws SignatureException 
	 * @throws KeyManagementException 
	 * @throws UnrecoverableKeyException 
	 * @throws Exception
	 */
	public String transfers(String appid,Long user_id,String openid,Double payAmount,String payDesc) throws UnrecoverableKeyException, KeyManagementException, SignatureException, PayApiException, PayBusinessException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {
		TransfersRO transfersRequest=new TransfersRO();
		BigDecimal amount=new BigDecimal(payAmount).multiply(fen);//支付金额 转换分
		transfersRequest.setAmount(amount.intValue());//企业付款金额，单位为分
		//WxApp wxApp=wxAppService.getApp(appid);
		String mch_id="1234567890";
		WxMerchant wxMerchant=wxMerchantService.getWxMerchant(mch_id);
		String mch_key=wxMerchant.getMch_key();
		transfersRequest.setMch_appid(appid);
		//transfersRequest.setCheck_name("NO_CHECK");//必填
		transfersRequest.setDesc(payDesc);//企业付款操作说明信息。必填
		//transfersRequest.setDevice_info(device_info);//微信支付分配的终端设备号 非必填
		transfersRequest.setMchid(mch_id);
		String nonce_str=RandomStringUtils.randomAlphanumeric(32);
		//String nonce_str=UUID.randomUUID().toString().replace("-", "");
		transfersRequest.setNonce_str(nonce_str);//随机字符串，不长于32位 必填
		transfersRequest.setOpenid(openid);
		String partner_trade_no=RandomStringUtils.randomAlphanumeric(32);
		transfersRequest.setPartner_trade_no(partner_trade_no);//商户订单号，需保持唯一性 必填
		//transfersRequest.setRe_user_name(re_user_name);//收款用户真实姓名。 如果check_name设置为FORCE_CHECK，则必填用户真实姓名
		//String spbill_create_ip = IWebUtils.getClientIp(request);//request.getRemoteAddr();
		String spbill_create_ip="127.0.0.1";
		transfersRequest.setSpbill_create_ip(spbill_create_ip);
		//TransfersResponse transfersResponse=RedPacketManager.transfers(wxMerchant.getCert(),mch_key,transfersRequest);
		String payment_no=null;//transfersResponse.getPayment_no();
		Map<String,Object> insert=new HashMap<String,Object>();
		//TODO 没有处理付款失败情况 需要使用原商户订单号重试
		insert.put("orderno", partner_trade_no);
		insert.put("payment_no", payment_no);
		insert.put("appid", appid);
		insert.put("user_id", user_id);
		insert.put("openid", openid);
		insert.put("amount", payAmount);
		insert.put("desc", payDesc);
		insert.put("status", 1);//0付款中1成功2失败
		insert.put("create_time", new Date());
		this.dbService.updateMapParameter("insert_wx_transfers", insert);
		return partner_trade_no;
		
	}
}
